//
//  MyImageView.m
//  iPictureSplitter
//
//  Created by Nikita Ivanyushchenko on 3/12/10.
//  Copyright 2010 MLS-Automatization. All rights reserved.
//

#import "MyImageView.h"


@implementation MyImageView
@synthesize hSize;
@synthesize vSize;

- (id)initWithCoder:(NSCoder *) coder
{
	if (self = [super initWithCoder:coder])
	{
		[self setEditable:YES];
		hSize = 1;
		vSize = 1;
	}
	return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];

	NSImage * img = [self image];
	
	CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
	NSRect selfRect = [self bounds];
	
	if (!img)
	{
		static NSString * idleText = @"Just drag image here!";
		
		NSFont * myFont = [NSFont fontWithName:@"Arial" size:16];
		NSMutableParagraphStyle * ps = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
		[ps setAlignment:NSCenterTextAlignment];
		
		NSDictionary * attsDict = [NSDictionary dictionaryWithObjectsAndKeys:
								   [NSColor blackColor], NSForegroundColorAttributeName,
								   myFont, NSFontAttributeName,
								   nil ];
		
		NSSize textSize = [idleText sizeWithAttributes:attsDict];
		
		[idleText drawAtPoint:NSMakePoint((selfRect.size.width - textSize.width)/2, (selfRect.size.height - textSize.height)/2) withAttributes:attsDict];
		return;
	}
	
	//calculate aspect ratios for correct draw lines of slicing
	float aspectRatioImg	= [img size].width/[img size].height;
	float aspectRatioView	= selfRect.size.width/selfRect.size.height;
	NSRect scaledRect = selfRect;
		
	if (aspectRatioImg > aspectRatioView)
	{
		scaledRect.size.height = scaledRect.size.width/aspectRatioImg;
		scaledRect.origin.y = (selfRect.size.height - scaledRect.size.height)/2;
	}
	else
	{
		scaledRect.size.width = scaledRect.size.height*aspectRatioImg;		
		scaledRect.origin.x = (selfRect.size.width - scaledRect.size.width)/2;
	}
	
	//set line color and width
	CGContextSetRGBStrokeColor(context, 1.f,1.f,0.f,1.f);
	CGContextSetLineWidth(context, 1.f);
	
	//draw lines
	CGContextBeginPath(context);
	
	//vertical lines
	for (int i=1;i<hSize;i++)
	{
		int x = scaledRect.origin.x + i*scaledRect.size.width/hSize;
		CGContextMoveToPoint(context, x, scaledRect.origin.y);
		CGContextAddLineToPoint(context, x, scaledRect.origin.y + scaledRect.size.height);
	}
	//horizontal lines
	for (int j=1;j<vSize;j++)
	{
		int y = scaledRect.origin.y + j*scaledRect.size.height/vSize;
		CGContextMoveToPoint(context, scaledRect.origin.x, y);
		CGContextAddLineToPoint(context, scaledRect.origin.x + scaledRect.size.width, y);		
	}
	CGContextClosePath(context);
	CGContextStrokePath(context);
}

@end
